Signature
● defines names and Data Types of Input Parameters (name:String, age:Int) (specifying Data Types is optional)
● defines Data Type of Return Value (String) (specifying Data Type is optional)
● arrow "->" inside Signature symbolizes that these Input Parameters are converted into this Output Parameter.
Since Closures can be stored inside Constants and Variables (including Input Function Parameters) Signature is used to say
what kind of Closure can be stored into a Constant or Variable.
For instance var name : Int says that Variable name can store Int Data Type.
Similarly var closure : (String, Int) -> (String) says that Variable closure can store Closure Data Type of specified Signature -
only Closures which accept String & Int as Input Parameters and return String.
When you store Closure inside Constant or Variable you can use them to call Closure (but without Named Parameters).
Parameter Names are only for internal use inside Closure's Body since Closure can't have Named Parameters when called.
Content
● Closure Syntax
● Closure Input Parameters (Parameters are not named)
● Closure Return Value (Return single Variable or Tuple or use Input-Output Parameters)
Closure is declared
● inside curly brackets { ... } { ... }
● starting by Closure's Signature (name:String, age:Int) -> (String) (accepts 2 Parameters & returns String)
● followed by Keyword in in
● followed by Closure's Statements return ("\(name) is \(age) years old")
Closure Syntax
//DECLARE VARIABLE THAT CAN HOLD CLOSURE DATA TYPE (OF SPECIFIED SIGNATURE).
var closureVariable : (String, Int) -> (String) //Closure that accepts 2 Parameters & returns String
//DECLARE CLOSURE. ASSIGN CLOSURE TO VARIABLE.
closureVariable = { (name:String, age:Int) -> (String) in return("\(name) is \(age) years old") }
closureVariable = { (name , age ) -> (String) in return("\(name) is \(age) years old") }
closureVariable = { (name , age ) in return("\(name) is \(age) years old") }
closureVariable = { name , age in return("\(name) is \(age) years old") }
//CALL CLOSURE. STORE RETURN VALUE INTO VARIABLE.
var result : String = closureVariable("John", 20) //Closure can't have named Parameters.
//DISPLAY RESULT.
print(result)